package com.dong.servlet.User;

import com.alibaba.fastjson.JSONArray;
import com.dong.pojo.Role;
import com.dong.pojo.User;
import com.dong.service.Role.RoleServiceImpl;
import com.dong.service.User.UserService;
import com.dong.service.User.UserServiceImpl;
import com.dong.util.Constants;
import com.dong.util.PageSupport;
import com.dong.util.pagesize;
import com.microsoft.sqlserver.jdbc.StringUtils;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null){
            this.updatePw(req,resp);
        }else if(method.equals("pwdmodify") && method != null){
            this.pwdModify(req,resp);
        }else if(method.equals("query") && method != null){
            this.query(req,resp);
        }else if(method.equals("view") && method != null){
            this.getUserByid(req,resp,"userview.jsp");
        }else if(method.equals("add") && method != null){
            this.addUser(req,resp);
        }else if(method.equals("ucexist") && method != null){
            this.userCodeExist(req,resp);
        }else if(method.equals("modify") && method != null){
            this.getUserByid(req,resp,"usermodify.jsp");
        }else if(method.equals("modifyexe") && method != null){
            this.modifyUser(req,resp);
        }else if(method.equals("deluser") && method != null){
            this.deleteUserById(req,resp);
        }
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //查询用户列表
    private void query(HttpServletRequest req, HttpServletResponse resp){


        //从前端获取数据
        String queryUsername = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<User> userList = null;
        List<Role> roleList = null;
        //第一次走这个请求，一定是第一页，页面大小固定
        int pageSize = pagesize.pageSize;
        int currentPageNo = 1;

        if(queryUsername == null){
            queryUsername = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询赋值
        }
        if(pageIndex != null){
            //可以加try/catch
            currentPageNo = Integer.parseInt(pageIndex);
        }
        //获取用户总数(分页上一页和下一页的情况)
        int totalCount = userService.getUserCount(queryUsername, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int)(totalCount/pageSize))+1;//总共有几页

        //控制首页和尾页
        //若果页面小于1，就显示第一页的东西
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){//当前页面大于总页数时返回最后一页
            currentPageNo = totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUsername, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);

        roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUsername);
        req.setAttribute("queryUserRole",queryUserRole);


        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    //修改密码
    private void updatePw(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if(o!=null && newpassword!=null){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if(flag){
                req.setAttribute("message","修改密码成功，请退出！使用新的密码重新登录！");
                //修改密码成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","修改密码失败！");
            }
        }else{
            req.setAttribute("message","新密码输入有误！");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //验证旧密码。因为用户登录会存在Session，所以不需要在进入到数据库中查询
    private void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        Map<String, String> resultMap = new HashMap<String, String>();

        if(o == null){//session失效了，过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) o).getUserPassword();
            if(userPassword.equals(oldpassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //通过用户id查找用户
    private void getUserByid(HttpServletRequest req,HttpServletResponse resp,String url) throws ServletException, IOException {
        String id = req.getParameter("uid");
        if(!StringUtils.isEmpty(id)){
            //调用方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserByid(id);
            req.setAttribute("user",user);
            req.getRequestDispatcher(url).forward(req,resp);
        }
    }
    //添加一个新用户
    private void addUser(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("add()================");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        if(userService.addUser(user)){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }
    }
    //判断添加用户中的userCode是否在数据库中存在
    private void userCodeExist(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //判断用户账号是否可用
        String userCode = req.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isEmpty(userCode)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode","exist");
        }else{
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if(user != null){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode","notexist");
            }
        }
        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的Write对象
        PrintWriter outPrintWriter = resp.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
    //修改一个用户的个人信息
    private void modifyUser(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("modify()================");
        String userid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(userid));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));

        UserService userService = new UserServiceImpl();
        if(userService.modifyUser(user)){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
        }
    }
    //删除用户个人信息
    private void deleteUserById(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String id = req.getParameter("uid");
        Integer delID = 0;
        try{
            delID = Integer.parseInt(id);
        }catch (Exception e) {
            // TODO: handle exception
            delID = 0;
        }

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delID <= 0){
            resultMap.put("delResult","notexist");
        }else{
            UserService userService = new UserServiceImpl();
            if(userService.deleteUserById(delID)){
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的Write对象
        PrintWriter outPrintWriter = resp.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
}
